package everyday;

import org.junit.jupiter.api.Test;

import java.util.LinkedList;
import java.util.Queue;

public class T1091 {
    public int shortestPathBinaryMatrix(int[][] grid) {
        int[][] direct = {{1, 1}, {-1, -1}, {1, -1}, {-1, 1}, {0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int n = grid.length;
        if (n == 1) return grid[0][0] == 0 ? 1 : -1;
        if (grid[0][0] == 1) return -1;
        boolean[][] b = new boolean[n][n];
        int res = 1;
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0});
        while (!queue.isEmpty()) {
            int len = queue.size();
            for (int i = 0; i < len; i++) {
                int[] old = queue.poll();
                if (old[0] == n - 1 && old[1] == n - 1) return res;
                for (int j = 0; j < 8; j++) {
                    int x = old[0] + direct[j][0];
                    int y = old[1] + direct[j][1];
                    if (x >= 0 && x < n && y >= 0 && y < n && !b[x][y] && grid[x][y] == 0) {
                        queue.offer(new int[]{x, y});
                        b[x][y] = true;
                    }
                }
            }
            res++;
        }
        return -1;
    }

    @Test
    public void test() {
        System.out.println(shortestPathBinaryMatrix(new int[][]{{0, 0, 0}, {1, 1, 0}, {1, 1, 0}}));
    }
}
